package com.springsecirtytest.activiti1.controller;

import com.springsecirtytest.activiti1.SecurityUtil;
import com.springsecirtytest.activiti1.util.AjaxResponse;
import com.springsecirtytest.activiti1.util.GlobalConfig;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.zip.ZipInputStream;

@RestController
@RequestMapping("/processDefinition")
public class ProcessDefinitionController {

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private SecurityUtil securityUtil;
    //获取流程定义

    @GetMapping("/getDefinitions")
    public AjaxResponse getDefinitions() {
        if (GlobalConfig.Test) {
            securityUtil.logInAs("bajie");
        }
        try {
            List<HashMap<String, Object>> hashMaps = new ArrayList<HashMap<String, Object>>();

            List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().list();

            for (ProcessDefinition processDefinition : list) {

                HashMap<String, Object> hashMap = new HashMap<String, Object>();
                hashMap.put("Name", processDefinition.getName());
                hashMap.put("Key", processDefinition.getKey());
                hashMap.put("ResourceName", processDefinition.getResourceName());
                hashMap.put("Version", processDefinition.getVersion());

                hashMaps.add(hashMap);
            }

            return AjaxResponse.Success(hashMaps);

        } catch (Exception e) {
            return AjaxResponse.ajaxData(GlobalConfig.ResponseCode.ERROR.getCode(), "获取流程失败", e.toString());
        }
    }

    @PostMapping(value = "/uploadStreamAndDeployment")
    public AjaxResponse uploadStreamAndDeployment(@RequestParam("processFile") MultipartFile multipartFile) {
        // 获取上传的文件名
        if (GlobalConfig.Test) {
            securityUtil.logInAs("bajie");
        }

        try {
            String fileName = multipartFile.getOriginalFilename();

            String extion = FilenameUtils.getExtension(fileName);

            InputStream fileInputStream = multipartFile.getInputStream();

            Deployment deployment = null;

            if (extion.equals("zip")) {
                ZipInputStream zipInputStream = new ZipInputStream(fileInputStream);
                deployment = repositoryService
                        .createDeployment()
                        .addZipInputStream(zipInputStream)
                        .name("部署zip")
                        .deploy();
            } else {
                deployment = repositoryService
                        .createDeployment()
                        .addInputStream(fileName, fileInputStream)
                        .name("部署2")
                        .deploy();

            }
            return AjaxResponse.Success(deployment);

        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResponse.ajaxData(GlobalConfig.ResponseCode.ERROR.getCode(), GlobalConfig.ResponseCode.ERROR.getDesc(), e);

        }
    }

    @PostMapping("/addDeploymentByString")
    public AjaxResponse addDeploymentByString(@RequestParam("processName") String stringBPMN, @RequestParam("deploymentName")
            String deploymentName) {

        try {

            Deployment deployment = repositoryService.createDeployment()
                    .addString("CreateWithBPMNJS.bpmn", stringBPMN)
                    .name(deploymentName)
                    .deploy();

            return AjaxResponse.ajaxData(GlobalConfig.ResponseCode.SUCCESS.getCode()
                    , GlobalConfig.ResponseCode.SUCCESS.getDesc()
                    , deployment.getId());

        } catch (Exception e) {
            return AjaxResponse.ajaxData(GlobalConfig.ResponseCode.ERROR.getCode(), GlobalConfig.ResponseCode.ERROR.getDesc(), e);

        }
    }

    //获取流程定义xml
    @GetMapping("/getDefinitionXml")
    public void getDefinitionXml(HttpServletResponse response
            , @RequestParam("deploymentID") String deploymentID
            , @RequestParam("resourceName") String resourceName) {

        try {

            InputStream inputStream = repositoryService.getResourceAsStream(deploymentID, resourceName);
            int count = inputStream.available();
            byte[] bytes = new byte[count];
            response.setContentType("text/xml");
            OutputStream outputStream = response.getOutputStream();
            while ((inputStream.read(bytes)) != -1) {
                outputStream.write(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @GetMapping("/getDeployments")
    public AjaxResponse getDeployments() {
    try {

        if (GlobalConfig.Test) {
            securityUtil.logInAs("bajie");
        }
        List<HashMap<String, Object>> listMaps = new ArrayList<HashMap<String, Object>>();
        List<Deployment> list = repositoryService.createDeploymentQuery().list();

        for (Deployment deployment : list) {
            HashMap<String, Object> hashMap = new HashMap<String, Object>();
            hashMap.put("ID", deployment.getId());
            hashMap.put("Name", deployment.getName());
            hashMap.put("deploymentTime", deployment.getDeploymentTime());

            listMaps.add(hashMap);
        }
        return AjaxResponse.ajaxData(GlobalConfig.ResponseCode.SUCCESS.getCode()
                , GlobalConfig.ResponseCode.SUCCESS.getDesc()
                , listMaps);
    }catch (Exception e) {
        return AjaxResponse.ajaxData(GlobalConfig.ResponseCode.ERROR.getCode(),
                "失败", e.toString());
    }
    }

    //删除流程定义
    @GetMapping(value = "/delDefinition")
    public AjaxResponse delDefinition(@RequestParam("depID") String depID, @RequestParam("pdID") String pdID) {
        try {
            repositoryService.deleteDeployment(pdID);
            return AjaxResponse.ajaxData(GlobalConfig.ResponseCode.SUCCESS.getCode()
                    , GlobalConfig.ResponseCode.SUCCESS.getDesc()
                    , "success");
        } catch (Exception e) {
            return AjaxResponse.ajaxData(GlobalConfig.ResponseCode.ERROR.getCode(),
                    "删除失败", e.toString());
        }
    }
}
